package com.itheima.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.CustomException_自定义异常;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.DishFlavor_菜品口味;
import com.itheima.reggie.pojo.Dish_菜品;
import com.itheima.reggie.pojo.SetmealDish_套餐与菜品;

import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: cl
 * @Date: 2022/4/3 - 04 - 03
 * @Description:
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish_菜品>
        implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishMapper dishMapper;


    //自定义多表查询分页查询
    @Override
    public PageInfo<DishDto> search(String name, int page, int size) {
        //设置分页插件数据
        PageHelper.startPage(page,size);

        System.out.println(page + "--------------------------------");

        //校验name是否为：name="    "
//        if (StringUtils.isEmpty(name)) {
//            name = null;
//        }

        //方式二：
        if (name!=null) {
            name = name.trim();
        }
        List<DishDto> search = dishMapper.search(name);

        PageInfo<DishDto> p = new PageInfo<>(search);
        return p;

    }


    /**
     * 添加菜品和口味
     *
     * @param dishDto
     */
    @Override
    @Transactional//因为操作了两张表，所以要开启事务，启动类也要加注解
    public void saveWithFlavor(DishDto dishDto) {
        //1、添加菜品信息
        this.save(dishDto);//dishService.save()

        //2、添加菜品口味信息(因为需要用到菜品的id  所以要获取并添加到口味实体类)
        Long id = dishDto.getId();

        //获取口味集合
        List<DishFlavor_菜品口味> flavors = dishDto.getFlavors();

        //通过stream流向集合中添加菜品id
        flavors = flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());

        //添加口味信息
        dishFlavorService.saveBatch(flavors);
    }


    /**
     * 根据id查询菜品和口味
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(long id) {
        //查询菜品
        Dish_菜品 dish = this.getById(id);
        //创建dishDto复制并记录口味
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish, dishDto);

        //查询口味

        LambdaQueryWrapper<DishFlavor_菜品口味> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor_菜品口味::getDishId, id);
        List<DishFlavor_菜品口味> dishFlavors = dishFlavorService.list(lqw);
        dishDto.setFlavors(dishFlavors);

        return dishDto;
    }


    /**
     * 修改菜品并修改对应口味
     *
     * @param dishDto
     */
    @Override
    @Transactional//因为操作了两张表，所以要开启事务，启动类也要加注解
    public void updateWithFlavor(DishDto dishDto) {

        //修改菜品
        this.updateById(dishDto);

        //更新口味，因为不同口味对应同一个dishId 所以不能通过ID修改
        //办法：先删除对应的口味，再重新添加

        //删除口味
        dishFlavorService.remove(
                Wrappers.<DishFlavor_菜品口味>lambdaQuery()
                        .eq(dishDto.getId() != null, DishFlavor_菜品口味::getDishId, dishDto.getId())
        );

        //添加口味(因为口味实体类中还没有记录dishId，先把id设置上)
        List<DishFlavor_菜品口味> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        //添加口味
        dishFlavorService.saveBatch(flavors);

    }

    //批量修改
    @Override
    public void updateStatus(int status, long[] ids) {
        dishMapper.updateStatus(status, ids);
    }

    /**
     * 删除菜品，并删除对应的口味和套餐中的菜品(不要真删除！修改删除字段为1)
     *
     * @param ids
     */
    @Override
    @Transactional
    public void removeByIdsWithFlavorAndSetmealDish(Long[] ids) {

        //select count(*) from dish where id in (1,2,3) and status = 1
        //查询菜品状态，确定是否可用删除
        LambdaQueryWrapper<Dish_菜品> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(Dish_菜品::getId, ids);
        queryWrapper.eq(Dish_菜品::getStatus, 1);

        int count = this.count(queryWrapper);
        if (count > 0) {
            //如果不能删除，抛出一个业务异常
            throw new CustomException_自定义异常("菜品正在售卖中，不能删除");
        }

        //能删除
        List<Long> longs = Arrays.asList(ids);
        //删除菜品
        //this.removeByIds(longs);
        Dish_菜品 dish = new Dish_菜品();
        dish.setIsDeleted(1);
        //删除后要停售
        dish.setStatus(0);
        this.update(dish,
                Wrappers.<Dish_菜品>lambdaUpdate()
                        .in(Dish_菜品::getId, ids)
        );

        //删除口味
//        dishFlavorService.remove(
//                Wrappers.<DishFlavor_菜品口味>lambdaQuery()
//                .in(DishFlavor_菜品口味::getDishId,ids)
//        );
        DishFlavor_菜品口味 dishFlavor = new DishFlavor_菜品口味();
        dishFlavor.setIsDeleted(1);
        dishFlavorService.update(dishFlavor,
                Wrappers.<DishFlavor_菜品口味>lambdaQuery()
                        .in(DishFlavor_菜品口味::getDishId, ids)
        );
        //删除套餐中的菜品
//        setmealDishService.remove(
//                Wrappers.< SetmealDish_套餐与菜品 >lambdaQuery()
//                .in(SetmealDish_套餐与菜品::getDishId,ids)
//        );

        SetmealDish_套餐与菜品 setmealDish = new SetmealDish_套餐与菜品();
        setmealDish.setIsDeleted(1);
        setmealDishService.update(setmealDish,
                Wrappers.<SetmealDish_套餐与菜品>lambdaQuery()
                        .in(SetmealDish_套餐与菜品::getDishId, ids)
        );
    }
}
